<template>
	<div class="addMaintainPlan zy-content">
		<back-level :goPage="back" />
		<Card :title="!editId ? '新增点检计划' : '编辑点检计划'" class="detail-content-layout">
			<div class="line-title">
				<Steps :current="current" class="steps">
					<Step title="选择点检对象"></Step>
					<Step title="添加点检内容"></Step>
					<Step title="创建点检时间"></Step>
				</Steps>
			</div>
			<!-- 第一步 -->
			<div class="searchBox" v-if="current === 0">
				<Form class="search-form" ref="stepOneValidate" :rules="stepOneRuleValidate" :model="formInline">
					<div class="labelTop">
						<FormItem label="点检计划" class="item" prop="planName">
							<Input
								type="text"
								v-model="formInline.planName"
								@on-change="planNamechange"
								:placeholder="`${$t('common.inputInfo')}`"
								clearable
								class="inputBorder"
								:maxlength="100"
							></Input>
						</FormItem>
					</div>
				</Form>
				<div class="addDev" @click="addDev">
					<Icon type="md-add-circle" size="20" />
					添加设备
				</div>
				<div class="tableContent">
					<Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" :columns="columns" :data="data">
						<template slot-scope="{ row }" slot="action">
							<span class="operationBtn" @click="deleteDevRow(row)">{{ $t('common.Delete') }}</span>
						</template>
					</Table>
				</div>
				<Modal :mask-closable="false" v-model="addDevVisible" title="添加设备" width="1400" class="addDevModal modal-content-layout">
					<Form class="search-form" label-position="top">
						<div class="label">
							<FormItem label="功能位置" class="item mr16">
								<Cascader
									clearable
									:data="orgList"
									v-model="searchParams.installPosition"
									:placeholder="`${$t('common.selectInfo')}`"
									change-on-select
								></Cascader>
							</FormItem>
							<FormItem label="设备编号" class="item mr16">
								<Input
									type="text"
									v-model="searchParams.deviceNo"
									:placeholder="`${$t('common.inputInfo')}`"
									class="inputBorder"
									:maxlength="32"
								></Input>
							</FormItem>
							<FormItem label="设备名称" class="item mr16">
								<Input
									type="text"
									v-model="searchParams.deviceName"
									:placeholder="`${$t('common.inputInfo')}`"
									class="inputBorder"
									:maxlength="32"
								></Input>
							</FormItem>
							<FormItem label="" class="item">
								<Button style="position: relative; top: 11px" class="ivu-btn-lg" type="primary" @click="changeNum">
									{{ $t('common.Query') }}
								</Button>
							</FormItem>
						</div>
					</Form>
					<div>
						<Table
							border
							class="resizable-table"
							@on-column-width-resize="onColumnWidthResize"
							ref="devSelection"
							:columns="addDevcolumns"
							:data="addDevdata"
							@on-selection-change="handleSelectionChange"
						></Table>
						<div class="pageWrap mt16">
							<pageLeftTitle :total="addDevpageParams.total" :selected="selectData.length" />
							<Page
								:total="addDevpageParams.total"
								:page-size="addDevpageParams.pageSize"
								:page-size-opts="$variable.pageSizes"
								:current="addDevpageParams.pageNum"
								@on-change="changePageNum"
								@on-page-size-change="changePageSize"
								show-sizer
								show-total
							/>
						</div>
					</div>
					<div slot="footer">
						<Button type="default" @click="addDevCancel">{{ $t('common.Cancle') }}</Button>
						<Button type="primary" @click="addDevOk">{{ $t('maintenance.Confirmed') }}</Button>
					</div>
				</Modal>
			</div>
			<!-- 第二步 -->
			<div v-if="current === 1" class="third searchBox" key="2">
				<!-- {{ contentData }} -->
				<div class="addPlan" @click="addPlan">
					<Icon type="md-add-circle" size="20" />
					添加点检内容
				</div>
				<div class="tableContent">
					<Table
						border
						class="resizable-table"
						@on-column-width-resize="onColumnWidthResize"
						ref="selection"
						:columns="contentColumns"
						:data="contentData"
					>
						<template slot-scope="{ row }" slot="action">
							<span class="operationBtn" @click="deleteRow(row)">{{ $t('common.Delete') }}</span>
						</template>
					</Table>
				</div>
				<Modal :mask-closable="false" v-model="visible" :title="`${$t('common.Detail')}`" class="checkContentModal" width="1200" footer-hide>
					<contentDetail :formInline="formInline" :materData="materData" :planToolList="toolList"></contentDetail>
				</Modal>
			</div>

			<!-- 第三步 -->
			<div v-if="current === 2" class="second" key="stepTwoValidate">
				<Form class="search-form" style="width: 100%" ref="stepTwoValidate" :rules="ruleValidate" :model="formInline">
					<Row :gutter="24">
						<Col span="12">
							<FormItem label="点检级别" class="item" prop="planLevel">
								<Select v-model="formInline.planLevel" :placeholder="`${$t('common.selectInfo')}`">
									<Option value="一级点检" label="一级点检"></Option>
									<Option value="二级点检" label="二级点检"></Option>
									<Option value="三级点检" label="三级点检"></Option>
								</Select>
							</FormItem>
						</Col>
						<Col span="9">
							<FormItem label="触发条件" prop="planCycle">
								<InputNumber style="width: 100%"  :min="1" v-model="formInline.planCycle" :placeholder="`${$t('common.inputInfo')}`"> </InputNumber>
							</FormItem>
						</Col>
						<Col span="3">
							<FormItem label="周期" prop="cycleUnit">
								<Select v-model="formInline.cycleUnit" :placeholder="`${$t('common.selectInfo')}`">
									<Option v-for="(item, index) in cycle" :key="index" :value="item.name" :label="item.name"></Option>
								</Select>
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="24">
						<Col span="12">
							<FormItem label="首次生成时间" class="item" prop="firstTime">
								<DatePicker
									type="datetime"
									format="yyyy-MM-dd HH:mm:ss"
									:placeholder="`${$t('common.selectInfo')}`"
									:value="formInline.firstTime"
									@on-change="
										(val) => {
											formInline.firstTime = val;
										}
									"
								>
								</DatePicker>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem label="计划截止时间" class="item" prop="endTime">
								<DatePicker
									type="datetime"
									format="yyyy-MM-dd HH:mm:ss"
									@on-change="
										(val) => {
											formInline.endTime = val;
										}
									"
									:placeholder="`${$t('common.selectInfo')}`"
									:value="formInline.endTime"
								></DatePicker>
							</FormItem>
						</Col>
					</Row>

					<Row :gutter="24">
						<Col span="12">
							<FormItem label="标准工时(min)" prop="planWorkhours">
								<InputNumber style="width: 100%"  :min="0" v-model="formInline.planWorkhours" :placeholder="`${$t('common.inputInfo')}`"> </InputNumber>
							</FormItem>
						</Col>
						<Col span="9">
							<FormItem
								label="任务存活时间"
								class="item"
								prop="liveTimeD"
								:rules="{
									required: true,
									message: '请输入任务存活时间',
									trigger: 'change',
									type: 'number',
								}"
							>
								<InputNumber style="width: 90%"  :min="0" v-model="formInline.liveTimeD" :placeholder="`${$t('common.inputInfo')}`"> </InputNumber>
								<span style="margin-left: 10px">天</span>
							</FormItem>
						</Col>
						<Col span="3">
							<FormItem
								label="小时"
								class="item"
								prop="liveTimeH"
								:rules="{
									required: true,
									message: '请输入',
									trigger: 'change',
									type: 'number',
								}"
							>
								<InputNumber style="width: 100%" :min="0" v-model="formInline.liveTimeH" :placeholder="`${$t('common.inputInfo')}`"> </InputNumber>
								<!-- <span style="margin-left: 10px;">小时</span> -->
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="24" class="mt16">
						<Col span="12">
							<FormItem label="点检任务是否需要主管确认" class="item" prop="isConfirm">
								<RadioGroup v-model="formInline.isConfirm">
									<Radio label="0">{{ $t('common.Yes') }}</Radio>
									<Radio label="1">{{ $t('common.No') }}</Radio>
								</RadioGroup>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem :label="$t('是否自动分配')" class="item" prop="isAllot">
								<RadioGroup v-model="formInline.isAllot">
									<Radio label="0">{{ $t('common.Yes') }}</Radio>
									<Radio label="1">{{ $t('common.No') }}</Radio>
								</RadioGroup>
							</FormItem>
						</Col>
					</Row>
				</Form>
			</div>

			<div class="nextBtn">
				<!-- {{ current }} -->
				<Button @click="previous" v-if="current !== 0">{{ $t('common.Pre') }}</Button>
				<Button type="primary" @click="next" v-if="current !== 2">{{ $t('common.Next') }}</Button>
				<Button type="primary" :loading="loading" @click="create" v-if="current === 2">
					{{ $t('common.Creatingsuccessful') }}
				</Button>
			</div>
		</Card>

		<Drawer title="添加点检内容" :styles="styles" :scrollable="true" v-model="drawerVisible" width="1200" class="drawer">
			<div class="search">
				<Col span="24">
					<Row>
						<Col span="6" style="padding: 0 5px">
							<label>点检项目</label>
							<Input v-model="searchPlanParams.checkName" clearable />
						</Col>
						<Col span="6" style="padding: 0 5px">
							<label>{{ $t('设备等级') }}</label>
							<Select v-model="searchPlanParams.deviceGrade" filterable clearable :placeholder="`${$t('common.selectInfo')}`" class="select">
								<Option v-for="v in category" :value="v.value" :key="v.value" :label="v.label"> </Option>
							</Select>
						</Col>
						<Col span="6" style="padding: 0 5px">
							<label>{{ $t('设备类别') }}</label>
							<Select v-model="searchPlanParams.deviceCategory" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
								<Option v-for="(item, index) of deviceTypeList" :value="item.value" :key="index" :label="item.value" />
							</Select>
						</Col>
						<Col span="6" style="padding: 0 5px">
							<label>{{ $t('equipCheck.SerialNo') }}</label>
							<Select
								v-model="searchPlanParams.deviceMId"
								filterable
								clearable
								:placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`"
								:remote-method="handleRemote"
							>
								<Option v-for="item in deviceMIdList" :value="item.deviceMId" :label="item.desc" :key="item.deviceMId" />
							</Select>
						</Col>
					</Row>
				</Col>
				<Col span="24" style="padding-top: 10px">
					<Row>
						<div style="display: flex; align-items: center; justify-content: flex-start">
							<Col span="6" style="padding: 0 5px">
								<label>点检周期</label>
								<Select v-model="searchPlanParams.cycleUnitStr" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
									<Option v-for="(item, index) of cycle" :value="item.key" :key="index" :label="item.name"> </Option>
								</Select>
							</Col>
							<Col span="6" style="padding: 0 5px">
								<label>备注</label>
								<Input v-model="searchPlanParams.remarks" filterable clearable :placeholder="`${$t('common.inputInfo')}`">
								</Input>
							</Col>
							<Col span="4">
								<Button type="primary" class="ivu-btn-lg" @click="changePlanNum">{{ $t('common.Query') }}</Button>
							</Col>
						</div>
					</Row>
				</Col>
			</div>
			<div class="tableContent" style="margin: 10px">
				<Table
					border
					class="resizable-table"
					@on-column-width-resize="onColumnWidthResize"
					ref="drawerSelection"
					:columns="drawerColumns"
					:data="drawerData"
					@on-selection-change="handleDrawerChange"
				></Table>
			</div>
			<div class="demo-drawer-footer">
				<Page
					:total="drawerTotal"
					:page-size="drawerpageSize"
					:page-size-opts="$variable.pageSizes"
					:current="drawerpageNum"
					@on-change="drawerchangePageNum"
					@on-page-size-change="drawerchangePageSize"
					show-sizer
					show-total
				/>

				<div>
					<Button class="ivu-btn-lg" style="margin-right: 8px" @click="handleDrawerCancel">{{ $t('common.Cancle') }} </Button>
					<Button class="ivu-btn-lg" type="primary" @click="handleDrawerOk">{{ $t('maintenance.Confirmed') }}</Button>
				</div>
			</div>
		</Drawer>
		<signle-common-modal ref="signleCommonModal" @handleRefresh="handleRefresh" />
	</div>
</template>

<script>
import recursion from '@/util/recursion';
import contentDetail from './contentDetail.vue';
// import util from '@/util/util'
import { mapGetters } from 'vuex';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import signleCommonModal from '@/views/devScene/repair/modules/signleCommonModal';
export default {
	name: 'addMaintainPlan',
	mixins: [toggleTableOperation],
	components: {
		contentDetail,
		signleCommonModal,
	},
	props: ['mainDevice', 'factoryList', 'planPositionList', 'planClassifyList', 'editId'],
	data() {
		return {
			customCacheKey: 'addMaintainPlanStep1',
			drawerTotal: 0,
			drawerpageSize: 10,
			drawerpageNum: 1,
			pageSizeOption: [10, 20, 30, 40],
			deviceMIdList: [],
			selectData: [],
			current: 0,
			visible: false,
			drawerVisible: false,
			loading: false,
			addDevVisible: false,
			disabledMinutes: [0, 10, 20],
			searchParams: {},
			searchPlanParams: {},
			styles: {
				height: 'calc(100% - 55px)',
				overflow: 'scroll',
				paddingBottom: '53px',
				position: 'static',
			},
			formInline: {
				planName: '',
				firstTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
				endTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
				liveTimeD: 0,
				liveTimeH: 0,
				planWorkhours: 0,
				cycleUnit: '',
				planCycle: 1,
			},
			stepOneRuleValidate: {
				categoryName: [{ required: true, message: '请选择设备类别', trigger: 'change' }],
				planName: [{ required: true, message: '请输入点检计划', trigger: 'blur' }],
			},
			ruleValidate: {
				planCycle: [
					{
						required: true,
						message: '请选择触发时间',
						trigger: 'blur',
						type: 'number',
					},
				],
				isAllot: [{ required: true, message: '请选择', trigger: 'blur' }],
				cycleUnit: [{ required: true, message: '请选择周期', trigger: 'change' }],
				planLevel: [{ required: true, message: '请选择点检级别' }],
				isConfirm: [{ required: true, message: '请选择是否需要' }],
				firstTime: [{ required: true, message: '请选择日期' }],
				endTime: [{ required: true, message: '请选择日期' }],
				liveTimeD: [
					{
						required: true,
						type: 'number',
						message: '请输入天数',
						trigger: 'blur',
					},
				],
				liveTimeH: [
					{
						required: true,
						type: 'number',
						message: '请输入小时',
						trigger: 'blur',
					},
				],
			},
			columns: [
				{
					type: 'index',
					width: 80,
					title: `${this.$t('common.index')}`,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('common.company')}`,
					key: 'brand',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('common.Installation')}`,
					key: 'installPositionName',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('设备类别')}`,
					key: 'deviceCategory',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('maintenance.EquipmentNo')}`,
					key: 'deviceNo',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('设备名称')}`,
					key: 'deviceName',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('资产编号')}`,
					key: 'assetCode',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('equipCheck.Model')}`,
					key: 'deviceSpec',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('common.operation')}`,
					slot: 'action',
					align: 'center',
					minWidth: 100,
				},
			],
			addDevcolumns: [
				{
					type: 'selection',
					width: 60,
					align: 'center',
				},
				{
					title: `${this.$t('common.company')}`,
					key: 'brand',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('common.Installation')}`,
					key: 'installPositionName',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('设备类别')}`,
					key: 'deviceCategory',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('maintenance.EquipmentNo')}`,
					key: 'deviceNo',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('ledger.EquipmentType')}`,
					key: 'deviceSpec',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('设备名称')}`,
					key: 'deviceName',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('资产编号')}`,
					key: 'assetCode',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
			],
			addDevdata: [],
			data: [],
			confirmedName: '',
			confirmedBy: '',
			materialList: {},
			toolList: [],
			materData: [],
			drawerSelectionData: [],
			category: [
				{ label: 'A', value: 'A' },
				{ label: 'B', value: 'B' },
				{ label: 'C', value: 'C' },
			],
			companyList: this.factoryList,
			position: this.planPositionList,
			classification: this.planClassifyList,
			levelList: [
				{ name: '一级点检', key: '1' },
				{ name: '二级点检', key: '2' },
				{ name: '三级点检', key: '3' },
			],
			cycle: [
				{ name: '小时', key: '8' },
				// { name: '班次', key: '7' },
				{ name: '日', key: '1' },
			],
			pageParams: {
				total: 64,
				pageSize: 10,
				pageNum: 1,
				pageSizeOption: [10, 20, 30, 40],
			},
			addDevpageParams: {
				total: 0,
				pageSize: 10,
				pageNum: 1,
				pageSizeOption: [50, 100, 150, 200],
			},
			contentColumns: [
				{
					type: 'index',
					width: 80,
					title: `${this.$t('common.index')}`,
					align: 'center',
				},
				// {
				//   title: '点检级别',
				//   key: 'checkLevel',
				//   align: 'center',
				//   minWidth: 100,
				//   tooltip: true,
				//   resizable: true,
				// },

				{
					title: '点检项目',
					key: 'checkName',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: '点检方式',
					key: 'checkMode',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: '需求人数',
					key: 'reqPNum',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: '显示顺序',
					key: 'sort',
					align: 'center',
					minWidth: 100,
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('common.operation')}`,
					slot: 'action',
					minWidth: 200,
					align: 'center',
				},
			],
			contentData: [],
			drawerColumns: [
				{
					type: 'selection',
					align: 'center',
					width: 60,
				},
				// {
				// 	title: `${this.$t('设备等级')}`,
				// 	key: 'deviceGrade',
				// 	minWidth: 80,
				// 	align: 'center',
				// 	resizable: true,
				// 	tooltip: true,
				// },
				// {
				// 	title: `${this.$t('设备类别')}`,
				// 	key: 'deviceCategory',
				// 	minWidth: 180,
				// 	align: 'center',
				// 	resizable: true,
				// 	tooltip: true,
				// },
				// {
				// 	title: `${this.$t('maintenance.EquipmentNo')}`,
				// 	key: 'deviceNo',
				// 	align: 'center',
				// 	minWidth: 100,
				// 	resizable: true,
				// 	tooltip: true,
				// },
				// {
				// 	title: `${this.$t('设备名称')}`,
				// 	key: 'deviceName',
				// 	align: 'center',
				// 	minWidth: 100,
				// 	resizable: true,
				// 	tooltip: true,
				// },
				// {
				// 	title: `${this.$t('设备流水号')}`,
				// 	key: 'deviceMId',
				// 	minWidth: 130,
				// 	align: 'center',
				// 	resizable: true,
				// 	tooltip: true,
				// },
				{
					title: `${this.$t('点检周期')}`,
					key: 'triggerCycleName',
					minWidth: 160,
					align: 'center',
					resizable: true,
					tooltip: true,
					render: (h, params) => {
						return h('div', [h('span', {}, params.row.cycleUnit.join(','))]);
					},
				},
				{
					title: `${this.$t('点检项目')}`,
					key: 'checkName',
					width: 200,
					align: 'center',
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('点检方式')}`,
					key: 'checkMode',
					width: 200,
					align: 'center',
					tooltip: true,
					resizable: true,
				},
				{
					title: `${this.$t('点检标准')}`,
					key: 'checkStandard',
					minWidth: 200,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('需求人数')}`,
					key: 'reqPNum',
					minWidth: 140,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
					{
					title: '备注',
					key: 'remarks',
					minWidth: 130,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('创建人')}`,
					key: 'realname',
					minWidth: 120,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('是否上传sop')}`,
					key: 'isCheckSop',
					align: 'center',
					minWidth: 130,
					resizable: true,
					tooltip: true,
				},
				// {
				// 	title: `${this.$t('安装位置')}`,
				// 	key: 'installPositionName',
				// 	align: 'center',
				// 	minWidth: 160,
				// 	tooltip: true,
				// 	resizable: true,
				// },
				{
					title: `${this.$t('创建时间')}`,
					key: 'createTime',
					minWidth: 200,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
			],
			otherColumns: [
				{
					type: 'selection',
					align: 'center',
					width: 60,
				},
				{
					title: `${this.$t('设备等级')}`,
					key: 'categoryName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('设备类别')}`,
					key: 'deviceType',
					minWidth: 180,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('maintenance.EquipmentNo')}`,
					key: 'deviceNo',
					align: 'center',
					minWidth: 100,
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('设备名称')}`,
					key: 'deviceName',
					align: 'center',
					minWidth: 100,
					resizable: true,
					tooltip: true,
				},
				{
					title: `${this.$t('设备流水号')}`,
					key: 'deviceMId',
					minWidth: 130,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
			],
			drawerData: [],
			deviceTypeList: [],
			deviceNameList: [],
			orgList: [],
			orgIdList: [],
			orgCodeList: [],
			materielNoList: [],
			deviceList: [],
		};
	},
	computed: {
		...mapGetters(['copyStatus']),
	},
	watch: {
		addDevVisible: function (val) {
			if (!val) {
				if (this.current == 1) {
					this.customCacheKey = 'addMaintainPlanStep2';
					this.getColumnWidth(this.contentColumns);
				}
				if (this.current == 0) {
					this.customCacheKey = 'addMaintainPlanStep1';
					this.getColumnWidth(this.columns);
				}
			}
		},
		drawerVisible: function (val) {
			if (!val) {
				if (this.current == 1) {
					this.customCacheKey = 'addMaintainPlanStep2';
					this.getColumnWidth(this.contentColumns);
				}
				if (this.current == 0) {
					this.customCacheKey = 'addMaintainPlanStep1';
					this.getColumnWidth(this.columns);
				}
			}
		},
	},
	created() {
		this.getColumnWidth(this.columns);

		if (this.editId) {
			this.getDetail(this.editId);
		}
		this.getOrgList();
	},
	mounted() {
		this.getFaultCategory('设备类别');
	},
	methods: {
		getDetail(id) {
			const that = this;
			this.axios({
				url: '/dms/devSpotCheckPlan/getDevSpotCheckPlanById',
				method: 'get',
				params: { id },
			}).then((res) => {
				that.getPlanDetail(res.data);
			});
		},
		chosePeople() {
			this.$refs.signleCommonModal.show({}, 'more', this.confirmedBy);
		},
		handleRefresh(userIds, userName) {
			this.confirmedName = userName.join(',');
			this.confirmedBy = userIds.join(',');
		},
		handleRemote(query) {
			if (!query) {
				return;
			}
			const fn = this.debounceSerach(() => {
				let _query = query.split('-');
				if (Array.isArray(_query)) _query = _query[0];
				this.axios({
					method: 'post',
					url: '/dms/device/page',
					data: {
						deviceMId: _query,
						pageSize: 100,
						pageNum: 1,
					},
				}).then((res) => {
					if (res.code === 200) {
						this.deviceMIdList = res.data.records.map((item) => {
							item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo;
							return item;
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				});
			}, 300);
			fn();
		},
		handleCasChange(val) {
			this.searchPlanParams.orgCode = val[val.length - 1];
		},
		drawerchangePageNum(val) {
			this.drawerpageNum = val;
			this.searchPlanList();
		},
		drawerchangePageSize(pageSize) {
			this.drawerpageSize = pageSize;
			this.searchPlanList();
		},
		debounceSerach(fn, delay) {
			let _this = this;
			return function f(...args) {
				if (_this.timeID) {
					clearTimeout(_this.timeID);
				}
				_this.timeID = setTimeout(() => {
					fn(args);
				}, delay);
			};
		},
		materielNoChange(val, value) {
			if (val && this.materielNoList.find((item) => item.materielNo + '-' + item.materielName === val)) {
				return;
			}

			const fn = this.debounceSerach(() => {
				const params = {
					deviceType: this.searchPlanParams.deviceType,
					param: val,
				};
				this.axios({
					method: 'post',
					// url: '/dms/applyUse/querySearch',
					url: '/dms/dmsBom/queryByDeviceTypeAndDeviceName',
					data: { ...params },
				}).then((res) => {
					if (res.code === 200) {
						if (res.data) {
							this.materielNoList = res.data;
						}
						if (value) {
							this.searchPlanParams.bomId = Number(value);
						}
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				});
			}, 360);
			fn();
		},
		deviceTypeChange(val) {
			if (this.data && this.data.length) {
				this.data = [];
			}
			if (this.contentData && this.contentData.length) {
				this.contentData = [];
			}
			if (val) {
				this.formInline.deviceType = val;
			}
		},
		//获取故障数据
		getFaultCategory(name) {
			this.axios({
				method: 'get',
				url: '/dms/faultCategory/basicDict',
				params: { name },
			}).then((res) => {
				if (res.code === 200) {
					if (name === '故障分类') {
						this.faultCategoryList = res.data.map((item) => {
							if (item.value) return item;
						});
					} else if (name === '设备类别') {
						this.deviceTypeList = res.data.map((item) => {
							if (item.value) return item;
						});
					}
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		planNamechange(val) {
			this.formInline.planName = JSON.parse(JSON.stringify(val.target.value));
			localStorage.setItem('planNameInfo', JSON.stringify(val.target.value));
		},
		levelChange() {
			if (this.contentData && this.contentData.length) {
				this.contentData = [];
			}
		},
		deviceNameChange() {
			if (this.data && this.data.length) {
				this.data = [];
			}
			if (this.contentData && this.contentData.length) {
				this.contentData = [];
			}
		},
		back() {
			this.$emit('handlePlanOk');
			// this.$emit("addMaintain", false);
		},
		getOrgList() {
			this.axios({
				method: 'get',
				url: '/basic/organization/findListByToken',
				params: {},
			}).then((res) => {
				if (res.code === 200) {
					const obj = {
						label: 'name',
						value: 'code',
						children: 'children',
					};
					this.orgList = recursion.convertTree(res.data, obj);
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		// 详情
		getPlanDetail(data) {
			const { ddevSpotCheckPlanRefs, ddevSpotCheckPlanSpotCheckRefs } = data;
			this.formInline = {
				...data,
			};
			this.contentData = ddevSpotCheckPlanSpotCheckRefs.map((item) => {
				return {
					checkId: item.checkId,
					checkName: item.checkName,
					sort: item.sort,
					checkMode: item.checkMode,
					reqPNum: item.reqPNum,
					checkLevel: item.checkLevel,
				};
			});
			this.data = ddevSpotCheckPlanRefs.map((item) => {
				return {
					deviceId: item.deviceId,
					brand: item.brand,
					installPositionName: item.installPositionName,
					deviceCategory: item.deviceCategory,
					assetCode: item.assetCode,
					deviceName: item.deviceName,
					deviceSpec: item.deviceSpec,
					deviceNo: item.deviceNo,
				};
			});
		},
		changePageSize(pageSize) {
			this.addDevpageParams.pageSize = pageSize;
			this.searchList();
		},
		changePageNum(val) {
			this.addDevpageParams.pageNum = val;
			this.searchList();
		},

		next() {
			if (this.current == 0) {
				this.customCacheKey = 'addMaintainPlanStep2';
				this.getColumnWidth(this.contentColumns);
				this.$refs['stepOneValidate'].validate((valid) => {
					if (valid) {
						if (!this.data.length) {
							this.$Message.warning({
								content: '请添加点检模具！',
								duration: 6,
								closable: true,
							});
							return false;
						}
						// 注视代码为校验是否重名
						if (!this.editId || this.copyStatus) {
							this.current += 1;
						} else {
							this.current += 1;
						}
					} else {
						return;
					}
				});
			} else if (this.current == 1) {
				if (!this.contentData.length) {
					this.$Message.warning({
						content: '请添加点检内容！',
						duration: 6,
						closable: true,
					});
					return false;
				}

				this.customCacheKey = 'addMaintainPlanStep2';
				this.getColumnWidth(this.contentColumns);

				// let hour = this.contentData.map(item => item.itemHours).reduce((pre, current) => Number(pre) + Number(current))
				// this.stepTwoValidate.itemHour = hour
				this.current += 1;
			} else {
				this.current += 1;
				this.customCacheKey = 'addMaintainPlanStep1';
				this.getColumnWidth(this.columns);
			}
		},
		previous() {
			this.current -= 1;
			if (this.current == 0) {
				this.customCacheKey = 'addMaintainPlanStep1';
				this.getColumnWidth(this.columns);
			}
			if (this.current == 0) {
				this.customCacheKey = 'addMaintainPlanStep2';
				this.getColumnWidth(this.contentColumns);
			}
		},
		create() {
			this.$refs.stepTwoValidate.validate((valid) => {
				if (valid) {
					const firstTimeinfo = new Date(this.formInline.firstTime).getTime();
					const nowTime = new Date().getTime();
					if (Number(firstTimeinfo) < Number(nowTime)) {
						this.$Message.warning({
							content: '首次生成时间必须大于当前时间！',
							duration: 6,
							closable: true,
						});
						return;
					}
					this.loading = true;
					const planName = JSON.parse(localStorage.getItem('planNameInfo'));
					let data = {
						...this.formInline,
						ddevSpotCheckPlanRefs: this.data.map((item) => {
							return {
								deviceId: item.deviceId,
							};
						}),
						ddevSpotCheckPlanSpotCheckRefs: this.contentData.map((item) => {
							return {
								checkId: item.checkId,
							};
						}),
						ddevspotcheckPLancontirmerRets: [
							{
								realname: '系统管理员',
								userId: 1,
							},
						],
					};
					if (planName) {
						data.planName = planName;
					}
					if (!this.editId || this.copyStatus) {
						this.axios({
							method: 'post',
							url: '/dms/devSpotCheckPlan/addDevSpotCheckPlan',
							data,
						})
							.then((res) => {
								if (res.code === 200) {
									this.$emit('handlePlanOk');
									this.$Message.success({
										content: '新增点检计划成功！',
										duration: 2,
										closable: true,
									});
								} else {
									this.$Message.warning({
										content: res.msg,
										duration: 6,
										closable: true,
									});
								}
							})
							.finally(() => {
								this.loading = false;
							});
					} else {
						// let params = {
						//   ...data,
						//   id: this.editId.id
						// }
						this.axios({
							method: 'post',
							url: '/dms/devSpotCheckPlan/updateDevSpotCheckPlan',
							data,
						})
							.then((res) => {
								if (res.code === 200) {
									this.$emit('handlePlanOk');
									this.$Message.success({
										content: '编辑点检计划成功！',
										duration: 2,
										closable: true,
									});
								} else {
									this.$Message.warning({
										content: res.msg,
										duration: 6,
										closable: true,
									});
								}
							})
							.finally(() => {
								this.loading = false;
							});
					}
				} else {
					// this.$Message.warning(({content: '请将信息填写完整！', duration: 6, closable: true}));
					return;
				}
			});
		},
		addDev() {
			this.customCacheKey = 'addMaintainPlanAddDevice';
			this.getColumnWidth(this.addDevcolumns);

			this.addDevcolumns.reverse().reverse();

			this.addDevVisible = true;
			this.$forceUpdate();
			// this.searchParams = {}
			this.searchList();
		},
		handleSelectionChange(selectionData) {
			let arr = selectionData.map((item) => {
				return {
					...item,
				};
			});
			this.selectData = arr;
		},
		addDevCancel() {
			this.addDevVisible = false;
			this.$refs.devSelection.selectAll(false);
		},
		addDevOk() {
			if (this.selectData.length == 0) {
				this.$Message.warning({
					content: '请选择设备！',
					duration: 6,
					closable: true,
				});
				return false;
			}
			let arr = this.data.filter((item) => this.selectData.some((x) => x.id == item.deviceId));
			if (arr.length) {
				this.$Message.warning({
					content: '有重复数据，请重新选择！',
					duration: 6,
					closable: true,
				});
				return false;
			}
			const data = this.selectData.map((item) => {
				return {
					deviceId: item.id,
					brand: item.brand,
					installPositionName: item.installPositionName,
					deviceCategory: item.deviceCategory,
					assetCode: item.assetCode,
					deviceName: item.deviceName,
					deviceSpec: item.deviceSpec,
					deviceNo: item.deviceNo,
				};
			});
			this.data.push(...data);
			this.addDevVisible = false;
			this.$refs.devSelection.selectAll(false);
		},
		handleChangeDevice(value) {
			console.log(value);
			// this.searchList()
		},
		//分页
		changeNum() {
			this.addDevpageParams.pageNum = 1;
			this.searchList();
		},
		searchList() {
			let data = {
				...this.searchParams,
				pageNum: this.addDevpageParams.pageNum,
				pageSize: this.addDevpageParams.pageSize,
				idList:this.data.map(item=>item.deviceId)
			};
			if (data.installPosition && data.installPosition.length > 0) {
				data.installPosition = [data.installPosition.at(-1)];
			} else delete data.installPosition;
			this.axios({
				method: 'POST',
				url: '/dms/device/page',
				data,
			}).then((res) => {
				if (res.code === 200) {
					this.addDevdata = res.data.records;
					this.addDevpageParams.total = res.data.total;
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		changePlanNum() {
			this.searchPlanList();
		},
		searchPlanList() {
			let data = {
				pageNum: this.drawerpageNum,
				pageSize: this.drawerpageSize,
				...this.searchPlanParams,
			};
			this.axios({
				method: 'POST',
				url: '/dms/devSpotCheck/getDevSpotCheckList',
				data,
			}).then((res) => {
				if (res.code === 200) {
					this.drawerData = res.data.records;
					this.drawerTotal = res.data.total;
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		handleDrawerChange(data) {
			this.drawerSelectionData = data;
		},
		addPlan() {
			this.customCacheKey = 'addMaintainPlanAddPlan';
			this.getColumnWidth(this.drawerColumns);

			this.drawerColumns.reverse().reverse();
			this.searchPlanParams = {};
			this.drawerVisible = true;
			this.searchPlanList();
		},
		handleDrawerCancel() {
			this.drawerVisible = false;
			this.$refs.drawerSelection.selectAll(false);
		},
		handleDrawerOk() {
			if (this.drawerSelectionData.length == 0) {
				this.$Message.warning({
					content: '请选择点检内容！',
					duration: 6,
					closable: true,
				});
				return false;
			}
			let arr = this.contentData.filter((item) => this.drawerSelectionData.some((x) => x.id == item.checkId));
			if (arr.length) {
				this.$Message.warning({
					content: '有重复数据，请重新选择！',
					duration: 6,
					closable: true,
				});
				return false;
			}
			const data = this.drawerSelectionData.map((item) => {
				return {
					checkId: item.id,
					checkName: item.checkName,
					sort: item.sort,
					checkMode: item.checkMode,
					reqPNum: item.reqPNum,
					checkLevel: item.checkLevel,
				};
			});
			this.contentData.push(...data);

			this.drawerVisible = false;
			this.$refs.drawerSelection.selectAll(false);
		},
		deleteRow(row) {
			this.contentData = this.contentData.filter((item) => item.checkId != row.checkId);
		},
		deleteDevRow(row) {
			this.data = this.data.filter((item) => item.deviceId != row.deviceId);
		},
	},
};
</script>

<style lang="scss">
.addMaintainPlan {
	background: #fff;

	.line-title {
		display: flex;
		justify-content: flex-start;
		font-size: 20px;
		padding: 10px;
		//border-bottom: 1px solid #dddddd;
		align-items: center;
		position: absolute;
		top: 3px;
		right: 0;

		.ivu-steps .ivu-steps-head,
		.ivu-steps-item.ivu-steps-status-process .ivu-steps-title {
			background: transparent;
		}

		.ivu-steps .ivu-steps-title {
			background: transparent;
			vertical-align: sub;
		}

		.back {
			color: #187bdb;
			font-size: 16px;
			padding-left: 20px;
			cursor: pointer;
		}

		.steps {
			width: 400px;
			margin-left: auto;
		}
	}

	.searchBox {
		.addDev {
			font-size: 16px;
			padding: 20px 0 0 10px;
		}

		.labelTop {
			display: flex;
			/*justify-content: space-between;*/
			border-bottom: 2px solid #d7d7d7;

			.item {
				width: 27%;
				margin: 0 10px 20px 10px;
			}
		}

		.label {
			display: flex;

			.item {
				margin-left: 10px;
			}
		}
	}

	.nextBtn {
		text-align: center;
		padding: 50px 0px;

		button {
			margin: 10px;
		}
	}
}

.second {
	.search-form {
		width: 30%;
	}
}

.third {
	.addPlan {
		font-size: 16px;
		padding: 20px 0 20px 10px;
	}
}

.addDevModal {
	.search-form {
		padding: 0;

		.label {
			display: flex;
		}
	}
}

.drawer {
	.search {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		button {
			margin: 20px 0 0 15px;
		}
	}

	.demo-drawer-footer {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
		padding: 0 30px 15px 30px;
		//text-align: right;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
	}
}
</style>
